const httpProxy = require('http-proxy')
const config = require('../configure')
const http = require('http')

const proxy = httpProxy.createProxyServer({
  target: config.rendererPublicPath
})

const _checkServer = () => 
  new Promise(resolve => {
    const client = http.get(
      config.rendererPublicPath, 
      (_, err) => {
        if (err) {
          resolve(false)
        } else {
          resolve(true)
        }
        client.destroy()
      }
    )

    client.on('error', (err) => {
      resolve(false)
    })
  })

// 间隔一分钟检查一次
let isServer = null
module.exports = {
  server (req, res) {
    proxy.web(req, res, { target: config.rendererPublicPath })
  },
  checkServer: async () => {
    if (isServer !== null) {
      return isServer
    }
    console.log('checkServer')
    isServer = await _checkServer()
    setTimeout(() => isServer = null, config.devCheckInterval)
    return isServer
  }
}

